package cn.yeziji.netty.adapter;

import cn.yeziji.forum.basic.netty.user.UserMessage;
import cn.yeziji.forum.common.key.RabbitMQConfig;
import cn.yeziji.netty.config.handler.NettyWebsocketHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.util.List;
import java.util.Map;

/**
 * 登出通知适配器
 *
 * @author gzkemays
 * @since 2022/11/09 1:25 PM
 */
@Slf4j
public class UserLogOutAdapter extends SelectedTypes<UserMessage> implements CommunicationAdapters {
  RabbitTemplate rabbitTemplate = getRabbitTemplate();
  NettyWebsocketHandler nettyWebsocketHandler = getNettyWebsocketHandler();

  public UserLogOutAdapter(Integer type, String text) {
    super(type, text, UserMessage.class);
    //    this.data = JSONObject.parseObject(text, UserMessage.class);
    this.data.setFlag(false);
  }

  @Override
  public void notice(ChannelHandlerContext channelHandlerContext) {
    log.info("用户 {} 登出", data.getNickname());
    // 通知 rabbitMQ 有用户登出
    rabbitTemplate.convertAndSend(
        RabbitMQConfig.USER_MSG_EXCHANGE, RabbitMQConfig.USER_MSG_ROUTING_KEY, data);
    // 删除 channel 和 用户信息关联
    Map<ChannelHandlerContext, UserMessage> connectUserMsg =
        nettyWebsocketHandler.getConnectUserMsg();
    connectUserMsg.remove(channelHandlerContext);
    List<ChannelHandlerContext> connectChannels = nettyWebsocketHandler.getConnectChannels();
    connectChannels.remove(channelHandlerContext);
  }

  @Override
  public Object dispose(ChannelHandlerContext channelHandlerContext) {
    return null;
  }
}
